from django.shortcuts import render
from django.http import HttpResponse
import json
import datetime
import markdown
import pathlib

from .models import *

# 考查方式
appraisal_methods = ["学校组织", "学院组织", "考查"]
# 课程性质
course_types = ['专业任选',
                '专业必修',
                '专业选修',
                '专业限选',
                '人文任选',
                '人文素质与艺术修养',
                '人文经典与人文修养',
                '公共必修',
                '其他任选',
                '创业教育',
                '国际视野与公民教育',
                '外语模块',
                '学科必修',
                '实践',
                '实践必修',
                '实践选修',
                '心理健康选修',
                '必修',
                '校定必修',
                '科技任选',
                '科技发展与科学精神',
                '经管任选',
                '艺术任选',
                '课外必修',
                '通识必修',
                '通识选修']
# 开课学院
institutes = ['人文艺术与数字媒体学院',
              '会计学院',
              '体育教学部',
              '党委学生工作部人民武装部学生处',
              '党委学生工作部人民武装部招生就业处创业学院',
              '卓越学院',
              '团委',
              '国有资产管理办公室',
              '图书馆',
              '外国语学院',
              '教务处',
              '机械工程学院',
              '材料与环境工程学院',
              '法学院',
              '理学院',
              '生命信息与仪器工程学院',
              '电子信息学院微电子学院',
              '管理学院',
              '经济学院',
              '网络空间安全学院浙江保密学院',
              '自动化学院人工智能学院',
              '计算机学院软件学院',
              '通信工程学院',
              '马克思主义学院']

# Create your views here.


def get_hash_code(string):
    sha256 = hashlib.sha256()
    sha256.update(string.encode('utf-8'))
    return sha256.hexdigest()


def verify_user(username, token):
    try:
        user = User.objects.get(pk=username)
        if(user.token == token):
            return True
        else:
            return False
    except:
        return False


def get_token(username, password):
    return get_hash_code(get_hash_code(username)+get_hash_code((password)))


def index(request):
    lessons = Lesson.objects.all().reverse().order_by('id')
    context = {
        'lessons': lessons,
    }
    return render(request, 'lesson/index.html', context)


def lessonpage(request, lessonid):
    context = {
        'lesson': Lesson.objects.get(pk=lessonid),
    }
    return render(request, 'lesson/lesson.html', context)


def like(request):
    id = request.POST['id']
    if request.POST['type'] == 'comment':
        likes = Comment.objects.get(pk=id).likeit()
        context = {
            'likes': likes,
        }
        return HttpResponse(json.dumps(context))
    else:
        likes = Lesson.objects.get(pk=id).likeit()
        context = {
            'likes': likes,
        }
        return HttpResponse(json.dumps(context))


def writecomment(request, lessonid):
    context = {
        'lesson': Lesson.objects.get(pk=lessonid),
    }
    return render(request, 'lesson/writecomment.html', context)


def handlecomment(request, lessonid):
    context = {'message': '未知错误', 'succeeded': False}
    if(verify_user(request.POST['username'], request.POST['token'])):
        comment = Lesson.objects.get(pk=lessonid).comment_set.create()
        comment.comment = request.POST['thoughts']
        try:
            if(request.POST['score'] != ''):
                try:
                    assert float(request.POST['score']) >= 0 and float(
                    request.POST['score']) <= 5
                    comment.score = float(request.POST['score'])
                except:
                    context['message'] = '绩点范围错误'
            try:
                assert request.POST['title'] != ''
                comment.title = request.POST['title']
                # 检测学期是否符合标准
                try:
                    assert request.POST['term'] != ''
                    term = request.POST['term'].split("-")
                    assert len(term) == 2
                    assert int(term[0]) >= 1956
                    assert int(term[1]) > 0 and int(term[1]) <= 3
                    comment.term = request.POST['term']
                    try:
                        comment.user = User.objects.get(
                            pk=request.POST['username'])
                        context['message'] = "提交成功ヾ(•ω•`)o"
                        context['succeeded'] = True
                    except:
                        context['message'] = "用户验证错误，试着重新登陆一下？"
                except:
                    context['message'] = "学期输入有误，请检查。学期应该是类似”2020-1”的形式。"
            except:
                context['message'] = "评论必需有标题 ψ(._. )>"
        except AssertionError as e:
            print(e)
            context['message'] = "绩点输入有误，请检查，成绩应该是 [0,100] 的浮点数。"
        except Exception as e:
            print(e)
    else:
        context['message'] = "用户认证失败，请重新登陆ψ(._. )>"
    if(context['succeeded']):
        comment.save()
    return HttpResponse(json.dumps(context))


def createlesson(request):
    return render(request, 'lesson/createlesson.html', {})


def handlelesson(request):
    lesson = Lesson()
    context = {'message': '', 'succeeded': False}
    if(verify_user(request.POST['username'], request.POST['token'])):
        try:
            if(not Lesson.objects.filter(name__contains=request.POST['name']) and request.POST['name']):
                lesson.name = request.POST['name']
                if(float(request.POST['credit']) >= 0 and float(request.POST['credit']) <= 5):
                    lesson.credit = float(request.POST['credit'])
                    if(request.POST['teacher']):
                        lesson.teacher = request.POST['teacher']
                        if(request.POST['appraisal_method']):
                            lesson.appraisal_method = appraisal_methods[int(
                                request.POST['appraisal_method'])]
                            if(request.POST['course_type']):
                                lesson.course_type = course_types[int(
                                    request.POST['course_type'])]
                                if(request.POST['period_start'] and int(request.POST['period_start']) > 0):
                                    lesson.period_start = int(
                                        request.POST['period_start'])
                                    if(request.POST['period_end'] and int(request.POST['period_end']) > lesson.period_start):
                                        lesson.period_end = int(
                                            request.POST['period_end'])
                                        if(request.POST['course_offering_institute']):
                                            lesson.course_offering_institute = institutes[int(
                                                request.POST['course_offering_institute'])]
                                            lesson.offering_class_now = bool(
                                                request.POST['offering_class_now'])
                                            lesson.save()
                                            context['message'] = "创建课程成功！"
                                            context['succeeded'] = True
                                        else:
                                            context['message'] = "开课学院输入错误！"
                                    else:
                                        context['message'] = "结束周错误！"
                                else:
                                    context['message'] = "起始周错误！"
                            else:
                                context['message'] = "课程性质输入错误！"
                        else:
                            context['message'] = "考核方式输入错误！"
                    else:
                        context['message'] = "老师必需非空！"
                else:
                    context['message'] = "学分数值范围错误！"
            else:
                print(Lesson.objects.filter(
                    name__contains=request.POST['name']))
                context['message'] = "课程名称重复！"
        except Exception as e:
            print(e)
            context['message'] = "未知错误"
    else:
        context['message'] = "用户认证失败，请重新登陆ψ(._. )>"
    return HttpResponse(json.dumps(context))


def search(request):
    keywords = request.POST['keywords']
    lessons = Lesson.objects.filter(name__icontains=keywords)
    lessons = lessons | Lesson.objects.filter(teacher__icontains=keywords)
    comments = Comment.objects.filter(comment__icontains=keywords)
    comments = comments | Comment.objects.filter(comment__icontains=keywords)
    context = {
        'lessons': lessons,
        'comments': comments,
    }
    return render(request, 'lesson/searchresults.html', context)


def generate_options(options):
    html_options = []
    for i in range(len(options)):
        html_options.append(r'<option value="' + str(i) +
                            r'">' + options[i] + r'</option>')
    print(html_options[i])


def render_signup_page(request):
    return render(request, 'lesson/signup.html')


def signup(request):
    username = request.POST['username']
    password = request.POST['password']
    context = {'message': '', 'succeeded': False}
    try:
        user = User.objects.get(pk=username)
        context['message'] = "用户名重复！"
    except:
        user = User(name=username, token=get_token(username, password))
        user.save()
        context['succeeded'] = True
    return HttpResponse(json.dumps(context))


def login(request):
    username = request.POST['username']
    password = request.POST['password']
    context = {'succeeded': False, 'token': '', 'message': ''}
    try:
        user = User.objects.get(pk=username)
        if(get_token(username, password) == user.token):
            context['succeeded'] = True
            context['token'] = user.token
            context['username'] = username
        else:
            context['message'] = '密码错误！'
    except:
        context['message'] = "用户不存在！"
    return HttpResponse(json.dumps(context))


def render_about_page(request):
    return render(request, 'lesson/about.html')
